package vip.zhenzicheng.algorithm.sort;

import vip.zhenzicheng.algorithm.util.ArrayUtils;

import java.util.Arrays;

/**
 * 归并排序
 *
 * @author zhenzicheng
 * @date 2022-06-07 18:06
 */
public class MergeSort {

  public static void main(String[] args) {
    int[] randomArray = ArrayUtils.getRandomArray(100, 50);
    mergeSort1(randomArray);
    System.out.println(Arrays.toString(randomArray));
  }

  // 递归方法实现
  public static void mergeSort1(int[] arr) {
    if (arr == null || arr.length < 2) {
      return;
    }
    process(arr, 0, arr.length - 1);
  }

  // arr[L,R]范上有序
  public static void process(int[] arr, int L, int R) {
    if (L == R) {
      return;
    }
    int mid = L + ((R - L) >> 1);
    process(arr, L, mid);
    process(arr, mid + 1, R);
    merge(arr, L, mid, R);
  }

  public static void merge(int[] arr, int L, int M, int R) {
    int[] help = new int[R - L + 1];
    int i = 0;
    int p1 = L;
    int p2 = M + 1;
    // 两个区间都没有越界
    while (p1 <= M && p2 <= R) {
      help[i++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++];
    }
    // p2越界
    while (p1 <= M) {
      help[i++] = arr[p1++];
    }
    // p1越界
    while (p2 <= R) {
      help[i++] = arr[p2++];
    }

    // for (i = 0; i < help.length; i++) {
    //   arr[L + i] = help[i];
    // }

    System.arraycopy(help, 0, arr, L, help.length); // 将区间从L开始全都重新拷贝正确顺序的元素
  }

  // 非递归
  public static void mergeSort2(int[] arr) {

  }

}
